//
//  LCPrintLabel.swift
//  Love
//
//  Created by boy on 2018/3/29.
//  Copyright © 2018年 boy. All rights reserved.
//

import UIKit
import AudioToolbox

class LCPrintLabel: UILabel {

    typealias PrintLabelCompleteBlock = () -> Void;
    
    /** 设置耽搁打字打印间隔,默认0.3秒 */
    var time: TimeInterval?
    /** 开始打印的位置索引，默认为0，即从头开始 */
    var currentIndex: NSInteger = 0
    /** 显示字体的颜色 */
    var prientColor: UIColor?
    /** 是否有打印的声音,默认为 YES */
    var hasSound: Bool?
    /** 打印完成的回调 */
    var completeBlock: PrintLabelCompleteBlock?
    
    private var soundID: SystemSoundID = 0
    private var prientTimer: Timer?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.textColor = UIColor.clear
        hasSound = true
        time = 0.3
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        prientTimer?.invalidate()
        prientTimer = nil
    }
    
    // MARK: - 开始打印
    func startPrint() {
        
        let path = Bundle.main.path(forResource: "printerVoice", ofType: "wav")
        let baseURL = NSURL.fileURL(withPath: path!)
        AudioServicesCreateSystemSoundID(baseURL as CFURL, &soundID)
        prientTimer = Timer.scheduledTimer(timeInterval: time!, target: self, selector: #selector(outPutWord), userInfo: nil, repeats: true)
    }
    
    @objc func outPutWord() {
        
        if (self.text?.count) == currentIndex {
            prientTimer?.invalidate()
            prientTimer = nil
            block(blockfunc: completeBlock)
        }else {
            currentIndex = currentIndex + 1
            let dict = [NSAttributedStringKey.foregroundColor : prientColor]
            let mutableString = NSMutableAttributedString(string: self.text!)
            mutableString.addAttributes(dict as Any as! [NSAttributedStringKey : Any], range: NSMakeRange(0, currentIndex))
            self.attributedText = mutableString
            hasSound! ? AudioServicesPlaySystemSound(soundID) : AudioServicesPlaySystemSound(0)
        }
    }
    
    func block(blockfunc: PrintLabelCompleteBlock!) {
        
        if (blockfunc) != nil {
            blockfunc()
        }
    }
}
